<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/27
 * Time: 15:56
 */

namespace app\admin\controller;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use Common\Oss;
use think\Session;

class Product extends Controller
{

    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @description: 审核商品数据接口
     * @return json
     */
    public function getAuthProduct()
    {
        $data = Request::instance()->post();
        // 查询筛选
        $where                 = [];
        $where['P.is_shelves'] = ['IN', '1,2'];
        if(array_key_exists('web_type',$data['search']))
        {
            if($data['search']['web_type'] == 'PRO_AUTH')
            {
                $where['P.is_shelves'] = ['EQ', 3];
                $where['P.status'] = ['EQ', 0];
            }
        }
        if (array_key_exists('search', $data) && !empty($data['search'])) {
            // 商品名称
            if (array_key_exists('name', $data['search']) && !empty($data['search']['name'])) $where['P.name'] = ['LIKE', '%' . trim($data['search']['name']) . '%'];
            if(array_key_exists('type', $data['search']) && !empty($data['search']['type']))
                $where['P.is_shelves'] = ['EQ', $data['search']['type']];
            // 商品分类
            if (array_key_exists('category', $data['search']) && !empty($data['search']['category'])) {
                if (array_key_exists('sel_cate_ids', $data['search']['category']) && !empty($data['search']['category']['sel_cate_ids'])) $where['P.category_id|P.type_id|P.small_type_id'] = ['IN',$data['search']['category']['sel_cate_ids']];
                if (array_key_exists('brand_ids', $data['search']['category']) && !empty($data['search']['category']['brand_ids'])) $where['P.brand_id'] = ['IN', implode(',', $data['search']['category']['brand_ids'])];
            }
        }
        // 商品列表
        $product['data'] = Db::name('product')
            ->alias('P')
            ->field('di.is_groom,su.name as su_name,P.origin,P.is_include_tax,P.image,P.id,P.name,P.stock,P.category_id,P.type_id,P.small_type_id,P.brand_id,S.price,P.is_shelves,S.specification')
            ->join('product_specification S', 'P.id = S.product_id','left')
            ->join('supplier su', 'su.id = P.supplier','left')
            ->where('S.is_default', 1)
            ->where($where)
            ->order('P.create_time desc')
            ->limit(($data['pageNumber'] - 1) * $data['pageSize'], $data['pageSize'])
            ->select();
        foreach ($product['data'] as $k => $v) {
            $product['data'][$k]['price']       =  sprintf("%.2f", $v['price']) .Session::get('flag');
            if($v['is_shelves'] == 1)
            {
                $product['data'][$k]['is_shelves']       = '已上架';
            }
            else if($v['is_shelves'] == 2)
            {
                $product['data'][$k]['is_shelves']       = '已下架';
            }
            $type                               = $this->getProductType([$v['category_id'], $v['type_id'], $v['small_type_id']]);
            $product['data'][$k]['category_id'] = $type['category'];
            $brand = Db::name('base_data')->field('name,name_english')->where('type_menu', 2)->where('id',$v['brand_id'])->find();
            $product['data'][$k]['brand_id']    = $brand['name'].'<br/>'.$brand['name_english'];
        }
        $product['pageNumber'] = $data['pageNumber'];
        if ($product['data'] === FALSE) return $result = json(Config::get('code.error'));
        // 商品总量
        $product['count'] = Db::name('product')
            ->alias('P')
            ->join('product_specification S', 'P.id = S.product_id')
            ->where('S.is_default', 1)
            ->where($where)
            ->count();
        return json($product);
    }

    /**
     * @writer:huangmingshuai
     * @DateTime:2018-02-027
     * @rewriter:
     * @rewriter_date:
     * @description: 获取所有品牌数据
     * @return json
     */
    public function getThreeBrand()
    {
        $info = Db::name('base_data')
            ->where(['type_menu' => 2, 'flag' => 1])
            ->select();
        if ($info)
        {
            $result = Config::get('code.success');
            $result['data'] = $info;
        }
        else
        {
           $result = json(Config::get('code.error'));
        }
        return json($result);
    }


    /**
     * @writer:阮飞宇
     * @DateTime:2018-01-25
     * @rewriter:
     * @rewriter_date:
     * @param $arr : 类别id、种类id、品牌id
     * @description: 获取商品类别、种类
     * @return json
     */
    public function getProductType($arr = array())
    {
        if (empty($arr)) {
            $type = Db::name('base_data')
                ->where('type_menu', 1)
                ->select();
            if ($type !== FALSE) {
                if (!empty($type)) {
                    $result         = Config::get('code.success');
                    $result['data'] = $type;
                } else {
                    $result = Config::get('code.null');
                }
            } else {
                $result = Config::get('code.error');
            }
        } else {
            if (is_array($arr)) {
                foreach ($arr as $v) {
                    $data[] = Db::name('base_data')
                        ->field('name')
                        ->where('type_menu', 1)
                        ->find($v)['name'];
                }
                if ($data !== FALSE) {
                    if (!empty($data)) {
                        $result['category']   = !empty($data[0]) ? $data[0] : NULL;
                        $result['type']       = !empty($data[1]) ? $data[1] : NULL;
                        $result['small_type'] = !empty($data[2]) ? $data[2] : NULL;
                        return $result;
                    }
                }
            }
            $result['category'] = $result['small_type'] = $result['type'] = NULL;
            return $result;
        }
        return json($result);
    }

    /**
     * 商品详情接口
     * @return \think\response\Json
     */
    public function getProductInfo()
    {
        $id = Request::instance()->post('id');
        if($id){
            $info = Db::name('product')
                ->alias('p')
                ->field('p.id,s.name as sname,p.name,p.image,p.stock,p.category_id,type_id,small_type_id,p.is_include_tax,p.origin')
                ->join('supplier s','p.supplier = s.id')
                ->where('p.id',$id)
                ->group('s.id')
                ->find();
            if($info){
                $info['spec_info'] = Db::name('product_specification')
                    ->where(['product_id'=>$info['id'],'flag'=>1])
                    ->select();
                foreach ($info['spec_info'] as $key => $value){
                    $info['spec_info'][$key]['price'] = sprintf("%.2f",$value['price']) .Session::get('flag');
                }
                 $res = Db::name('base_data')
                            ->field('CONCAT_WS(\'/\',`name`,`name_english`) as name')
                            ->whereIn('id',[$info['category_id'],$info['type_id'],$info['small_type_id']])
                            ->where('type_menu',1)->select();
                $type = '';
                foreach ($res as $v){
                    $type.=$v['name'].' - ';
                }
                $info['type'] = substr($type,'0',strlen($type)-3);
                $result = Config::get('code.success');
                $result['data'] = $info;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * 商品审核接口
     * @return \think\response\Json
     */
    public function productAuth()
    {
        $data = Request::instance()->post();
        if (array_key_exists('type' , $data) && array_key_exists('id' , $data))
        {
            if($data['type'] == 1)
            {
                $status = Db::name('product')->where('id',$data['id'])->update(['status' => 1,'is_shelves'=>1]);
                if($status)
                {
                    $result = Config::get('code.success');
                }
                else
                {
                    $result = Config::get('code.error');
                }
            }
            else if($data['type'] == 2)
            {
                if(array_key_exists('message' , $data))
                {
                    $status = Db::name('product')->where('id',$data['id'])->update(['status' => 2 ,'is_shelves' => 5]);
                    if($status)
                    {
                        $ins_data['product_id'] = $data['id'];
                        $ins_data['message'] = $data['message'];
                        $ins_data['create_time'] = date('Y-m-d H:i:s');
                        $status = Db::name('product_auth')->insert($ins_data);
                        if($status)
                        {
                            $result = Config::get('code.success');
                        }
                        else
                        {
                            $result = Config::get('code.error');
                        }
                    }
                    else
                    {
                        $result = Config::get('code.error');
                    }
                }
                else
                {
                    $result = Config::get('code.mistake');
                }
            }
            else
            {
                $result = Config::get('code.mistake');
            }
        }
        else
        {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }


    /**
     * @return \think\response\Json
     */
    public function getBusinessInfo()
    {
        $info = Db::name('base_data')->where('parent_id',0)->where('type_menu',1)->where('flag',1)->select();
        if($info)
        {
            $result = Config::get('code.success');
            $result['data'] = $info;
        }
        else
        {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * 获取商品类型数据(三级)
     * @return \think\response\Json
     */
    public function getProductTypeInfo()
    {
        $info = Db::name('base_data')
            ->field('CASE WHEN NAME IS NULL THEN name_english ELSE NAME END as name,name_english as namEn,id,level')
            ->where(['parent_id' => 0 ,'type_menu'=>1,'status' => 1])
            ->select();
        if($info)
        {
            foreach ($info as $key=>$value)
            {
                $info1 = Db::name('base_data')
                    ->field('CASE WHEN NAME IS NULL THEN name_english ELSE NAME END as name,name_english as namEn,id')
                    ->where(['parent_id'=> $value['id'] ,'type_menu'=>1 ,'status' => 1])
                    ->select();
                if($info1)
                {
                    foreach ($info1 as $k => $v)
                    {
                        $info2 = Db::name('base_data')
                            ->field('CASE WHEN NAME IS NULL THEN name_english ELSE NAME END as name,name_english as namEn,id')
                            ->where(['parent_id'=> $v['id'] ,'type_menu'=>1 , 'status' => 1])
                            ->select();
                        if($info2)
                        {
                            foreach ($info2 as $ke => $val)
                            {
                                $info2[$ke]['isParent'] = false;
                                $info2[$ke]['children'] = [];
                            }
                        }
                        $info1[$k]['children'] = $info2;
                        $info1[$k]['isParent'] = false;
                    }
                }
                $info[$key]['children'] = $info1;
                $info[$key]['isParent'] = false;
            }
        }
        return json($info);
    }


    /**
     * 获取商品类型数据(二级)
     * @return \think\response\Json
     */
    public function getProductTypeInfo2()
    {
        $info = Db::name('base_data')->field('id,name,name_english as namEn')->where(['parent_id' => 0 ,'type_menu'=>1 , 'flag' => 1])->select();
        if($info)
        {
            foreach ($info as $key=>$value)
            {
                $info1 = Db::name('base_data')->field('id,name,name_english as namEn')->where(['parent_id'=> $value['id'] ,'type_menu'=>1 ,'flag' => 1])->select();
                if($info1)
                {
                    foreach ($info1 as $k => $v)
                    {
                        $info1[$k]['children'] = [];
                        $info1[$k]['isParent'] = false;
                    }
                }
                $info[$key]['children'] = $info1;
                $info[$key]['isParent'] = false;
            }
        }
        return json($info);
    }
    /**
     * 获取商品类型数据(三级)
     * @return \think\response\Json
     */
    public function getProductTypeInfo3()
    {
//        SELECT CASE WHEN NAME IS NULL THEN name_english ELSE NAME END as name FROM base_data
        // $info = Db::name('base_data')->field('id,parent_id,CASE WHEN name IS NULL THEN name_english ELSE name END as name,name_english as namEn')->where(['flag' => 1])->select();
                $info = Db::name('base_data')->field('id,name,name_english as namEn,level')->where(['parent_id'=>0,'flag' => 1])->select();
        // $data = [];
        // if ($info){
        //     foreach ($info as $key => $value) {
        //         if ($value['parent_id'] == 0){
        //         $data[$key]= $value;
        //         $data[$key]['children']= [];
        //         $data[$key]['isParent']=false;
        //         }
        //         foreach ($info as $key1 => $value1) {
        //             if ($value1['parent_id'] == $value['id']){
        //             $data[$key]['children'][$key1]= $value1;
        //             $data[$key]['children'][$key1]['children']= [];
        //             $data[$key]['children'][$key1]['isParent']=false;
        //             }
        //             foreach ($info as $key2 => $value2) {
        //                 if ($value2['parent_id'] == $value1['id']){
        //                 $data[$key]['children'][$key1]['children'][$key2]= $value2;
        //                 $data[$key]['children'][$key1]['children'][$key2]['children']= [];
        //                 $data[$key]['children'][$key1]['children'][$key2]['isParent']=false;
        //                 }
        //             }
        //         }
                
        //     }
        // }
        // return json($data);
        
        if($info){
            foreach ($info as $key=>$value){
                $info1 = Db::name('base_data')
                    ->field('id,CASE WHEN NAME IS NULL THEN name_english ELSE NAME END as name,name_english as namEn,level')
                    ->where(['parent_id'=> $value['id'] ,'flag' => 1])->select();
                if($info1){
                    foreach ($info1 as $k => $v){
                        $info2 = Db::name('base_data')
                            ->field('id,CASE WHEN NAME IS NULL THEN name_english ELSE NAME END as name,name_english as namEn,level')
                            ->where(['parent_id'=> $v['id'] ,'flag' => 1])->select();
                        if ($info2){
                            foreach ($info2 as $kk=>$vv){
                                $info2[$kk]['children'] = [];
                                $info2[$kk]['isParent'] = false;
                            }
                        }
                        $info1[$k]['children'] = $info2;
                        $info1[$k]['isParent'] = false;
                    }
                }
                $info[$key]['children'] = $info1;
                $info[$key]['isParent'] = false;
            }
        }
        return json($info);
    }

    /**
     * @return \think\response\Json
     */
    public function addProductType()
    {
        $data = Request::instance()->post();
        if($data){
            if(!empty($data['name_english']) && !empty($data['type'])){
                $where  = [
                    'name_english'  => $data['name_english'],
                    'flag'          => 1
                ];
                $where1  = [
                    'name'          => $data['name'],
                    'flag'          => 1
                ];
                $count1 = 0;
                if ($data['type'] == 1){
                    $count  = Db::name('base_data')->where($where)->count();
                    $count1 = Db::name('base_data')->where($where1)->count();
                }else{
                    $count = Db::name('base_data')->where($where)->count();
                }
                if ($count>0 || $count1>0){
                    $result['status']   = 209;
                    $result['msg']      = "该名称已存在";
                    return json($result);
                }
                if ($data['level'] === 2){
                    $ins_data['leaf']   = 1;
                    $ins_data['level']  = $data['level'] + 1;
                }else if ($data['level'] === 0 || $data['level'] === 1){
                    $ins_data['leaf']   = 0;
                    $ins_data['level']  = $data['level'] + 1;
                }else{
                    $ins_data['leaf']   = 0;
                    $ins_data['level']  = 0;
                }
                if (!empty($data['name'])){
                    $ins_data['name'] = $data['name'];
                }
                $ins_data['name_english']   = $data['name_english'];
                $ins_data['parent_id']      = $data['parent_id'];
                $ins_data['flag']           = 1;
                if ($data['type'] == 1){
                    $ins_data['type_name']  = '种类';
                    $ins_data['type_menu']  = 1;
                }
                if ($data['type'] == 2){
                    $ins_data['type_name']  = '品牌';
                    $ins_data['type_menu']  = 2;
                }
                if (isset($data['image'])){
                    $ins_data['image'] = $data['image'];
                }else{
                    $ins_data['image'] ='';
                }
                $ins_data['create_time']    = date('Y-m-d H:i:s',time());
                $status = Db::name('base_data')->insert($ins_data);
                if($status){
                    $result = Config::get('code.success');
                } else {
                    $result = Config::get('code.error');
                }
            } else {
                $result = Config::get('code.mistake');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * 获取商品类型列表数据
     * @return \think\response\Json
     */
    public function getProductTypeLine()
    {
        //$data = Request::instance()->post();
//        $where['id|parent_id'] = ['EQ',90];
        $where = [];
        $where['flag'] = ['EQ',1];
       // if(!empty($data['name'])) $where['name'] = ['like' , '%'.$data['search']['name'].'%'];
        $info = Db::name('base_data')->field('id,name,name_english,image,parent_id,level,type_menu,goods_num')->where('flag',1)->select();
        if($info) {
            foreach ($info as $key => $value) {
				$num = 0;
				foreach($info as $k=>$v){
					if($value['id'] == $v['parent_id']){
						$num ++;
					}
				}
				//$info[$key]['number'] = Db::name('base_data')->where('parent_id' , $value['id'])->where('flag',1)->count();
				$info[$key]['number'] = $num;
                //if($value['parent_id'] == 0) {
                //    unset($info[$key]['parent_id']);
                //}
                if ($value['type_menu'] == 2){
                    $info[$key]['name'] = $value['name_english'];
                }
				
                $info[$key]['level'] = $value['level'] + 1;
                $info[$key]['goods_number'] = $value['goods_num'];
            }
            $result = Config::get('code.success');
            $result['data'] = $info;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

//    public function test(){
//        for($i=0;$i<=170;$i++){
//            $a = Db::execute("update base_data SET goods_num = (SELECT count(*) from product where small_type_id = $i) where id =$i");
//        }
//        return json($a);
//    }
    /**
     * 获取商品分类详情
     * @return \think\response\Json
     */
    public function getProdctTypeInfoById()
    {
        $id = input('post.id');
        if ($id){
            $info = Db::name('base_data')->where('id' , $id )->find();
            if($info) {
                $info['parent_name'] = Db::name('base_data')->where('id' , $info['parent_id'])->value('name');
                $result = Config::get('code.success');
                $result['data'] = $info;
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * 修改商品分类s
     * @return \think\response\Json
     */
    public function saveTypeInfo()
    {
        $data = Request::instance()->post();
        if(!empty($data['id']) && !empty($data['name_english'])) {
			//$where['level'] = $data['level'];
            //$where  = [
            //    'name_english'  => $data['name_english'],
            //    'flag'          => 1,
            //    'id'            => ['<>',$data['id']],
            //];
            //$where1  = [
            //    'name'          => $data['name'],
            //    'flag'          => 1,
            //    'id'            => ['<>',$data['id']],
            //];
            $where  = [
                'name_english'  => $data['name_english'],
                'flag'          => 1,
                'id'            => ['<>',$data['id']],
                'level' => $data['level'],
            ];
            $where1  = [
                'name'          => $data['name'],
                'flag'          => 1,
                'id'            => ['<>',$data['id']],
                'level' => $data['level'],
            ];
            $count1 = 0;

            if ($data['type'] == 1){
                $count  = Db::name('base_data')->where($where)->count();

                $count1 = Db::name('base_data')->where($where1)->count();
            }else{
                $count  = Db::name('base_data')->where($where)->count();
            }
			
            if ($count>0 || $count1>0){
                $result['status']   = 209;
                $result['msg']      = "该名称或英文名称已存在";
                return json($result);
            }
            if ($data['level'] === 2){
                $save_data['leaf']      = 1;
                $save_data['level']     = $data['level'] + 1;
            }else if ($data['level'] === 0 || $data['level'] === 1){
                $save_data['leaf']      = 0;
                $save_data['level']     = $data['level'] + 1;
            }else{
                $save_data['leaf']      = 0;
                $save_data['level']     = 0;
            }
            if (!empty($data['name'])){
                $save_data['name']      = $data['name'];
            }
            if (isset($data['image'])){
                $save_data['image'] = $data['image'];
            }else{
                $save_data['image'] ='';
            }
            $save_data['name_english']  = $data['name_english'];
            $save_data['parent_id']     = $data['parent_id'];
            $status = Db::name('base_data')->where('id' , $data['id'])->update($save_data);
			
            //if($status!=false) {
            //    $result = Config::get('code.error');
            //} else {
            //    $result = Config::get('code.success');
            //}
			$result = Config::get('code.success');
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * 商品分类删除（逻辑删除）
     * @return \think\response\Json
     */
    public function saveProTypeStatus()
    {
        $data   = Request::instance()->post();
        $id     = $data['id'];
        $level  = $data['level'] - 1;
        if ($level == 0){
            $product = Db::table('product')->where('category_id',$id)->where(['status'=>1,'is_shelves'=>1])->count();
            if ($product==0){
                $ids = Db::table('base_data')->field('id')->where('parent_id',$id)->where('flag',1)->select();
                foreach ($ids as $k=>$v){
                    $product1 = Db::table('product')->where('type_id',$v['id'])->where(['status'=>1,'is_shelves'=>1])->count();
                    if ($product1 == 0){
                        $ids1 = Db::table('base_data')->field('id')->where('parent_id',$v['id'])->where('flag',1)->select();
                        foreach ($ids1 as $kk=>$vv){
                            $product2 = Db::table('product')->where('small_type_id',$vv['id'])->where(['status'=>1,'is_shelves'=>1])->count();
                            if ($product2 == 0){
                                $ids2 = Db::table('base_data')->field('id')->where('parent_id',$vv['id'])->where('flag',1)->select();
                                foreach ($ids2 as $key=>$value){
                                    $product3 = Db::table('product')->where('brand_id',$value['id'])->where(['status'=>1,'is_shelves'=>1])->count();
                                    if ($product3 == 0){
                                        $res = Db::name('base_data')->where('id', $value['id'])->update(['flag' => 0]);
                                        if ($res){
                                            $result = Config::get('code.success');
                                        }else{
                                            $result = Config::get('code.error');
                                        }
                                    }else{
                                        $result['msg']      = '该类别下还有上架的商品';
                                        $result['status']   = 201;
                                        return json($result);
                                    }
                                }
                                $res = Db::name('base_data')->where('id', $vv['id'])->update(['flag' => 0]);
                                if ($res){
                                    $result = Config::get('code.success');
                                }else{
                                    $result = Config::get('code.error');
                                }
                            }else{
                                $result['msg']      = '该类别下还有上架的商品';
                                $result['status']   = 201;
                                return json($result);
                            }
                        }
                        $res = Db::name('base_data')->where('id', $v['id'])->update(['flag' => 0]);
                        if ($res){
                            $result = Config::get('code.success');
                        }else{
                            $result = Config::get('code.error');
                        }
                    }else{
                        $result['msg']      = '该类别下还有上架的商品';
                        $result['status']   = 201;
                        return json($result);
                    }
                }
                $res = Db::name('base_data')->where('id', $id)->update(['flag' => 0]);
                if ($res){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }else{
                $result['msg']      = '该类别下还有上架的商品';
                $result['status']   = 201;
                return json($result);
            }
        }elseif ($level == 1){
            $product = Db::table('product')->where('type_id',$id)->where(['status'=>1,'is_shelves'=>1])->count();
            if ($product==0){
                $ids = Db::table('base_data')->field('id')->where('parent_id',$id)->where('flag',1)->select();
                foreach ($ids as $k=>$v){
                    $product1 = Db::table('product')->where('small_type_id',$v['id'])->where(['status'=>1,'is_shelves'=>1])->count();
                    if ($product1 == 0){
                        $ids1 = Db::table('base_data')->field('id')->where('parent_id',$v['id'])->where('flag',1)->select();
                        foreach ($ids1 as $kk=>$vv){
                            $product2 = Db::table('product')->where('brand_id',$vv['id'])->where(['status'=>1,'is_shelves'=>1])->count();
                            if ($product2 == 0){
                                $res = Db::name('base_data')->where('id', $vv['id'])->update(['flag' => 0]);
                                if ($res){
                                    $result = Config::get('code.success');
                                }else{
                                    $result = Config::get('code.error');
                                }
                            }else{
                                $result['msg']      = '该类别下还有上架的商品';
                                $result['status']   = 201;
                                return json($result);
                            }
                        }
                        $res = Db::name('base_data')->where('id', $v['id'])->update(['flag' => 0]);
                        if ($res){
                            $result = Config::get('code.success');
                        }else{
                            $result = Config::get('code.error');
                        }
                    }else{
                        $result['msg']      = '该类别下还有上架的商品';
                        $result['status']   = 201;
                        return json($result);
                    }
                }
                $res = Db::name('base_data')->where('id', $id)->update(['flag' => 0]);
                if ($res){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }else{
                $result['msg']      = '该类别下还有上架的商品';
                $result['status']   = 201;
                return json($result);
            }
        }elseif ($level == 2){
            $product = Db::table('product')->where('small_type_id',$id)->where(['status'=>1,'is_shelves'=>1])->count();
            if ($product == 0){
                $ids = Db::table('base_data')->field('id')->where('parent_id',$id)->where('flag',1)->select();
                foreach ($ids as $k=>$v){
                   $product1 = Db::table('product')->where('brand_id',$v['id'])->where(['status'=>1,'is_shelves'=>1])->count();
                   if ($product1 == 0){
                       $res = Db::name('base_data')->where('id', $v['id'])->update(['flag' => 0]);
                       if ($res){
                           $result = Config::get('code.success');
                       }else{
                           $result = Config::get('code.error');
                       }
                   }else{
                       $result['msg']      = '该类别下还有上架的商品';
                       $result['status']   = 201;
                       return json($result);
                   }
                }
                $res = Db::name('base_data')->where('id', $id)->update(['flag' => 0]);
                if ($res){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }else{
                $result['msg']      = '该类别下还有上架的商品';
                $result['status']   = 201;
                return json($result);
            }
        }elseif ($level == 3){
            $info = Db::table('product')->where('brand_id',$id)->where(['status'=>1,'is_shelves'=>1])->count();
            if ($info == 0){
               $res = Db::name('base_data')->where('id', $id)->update(['flag' => 0]);
               if ($res){
                   $result = Config::get('code.success');
               }else{
                   $result = Config::get('code.error');
               }
            }else{
                $result['msg']      = '该类别下还有上架的商品';
                $result['status']   = 201;
                return json($result);
            }
        }
            /*$two_info = Db::name('base_data')->field('id')->where('parent_id',$id)->select();
            if($two_info) {
                $arr2 = [];
                foreach ($two_info as $key => $value) {
                    $res = Db::name('product')->where('category_id|type_id|small_type_id','eq',$value['id'])->find();
                    if(empty($res)) {
                        $arr2[$key] = $value['id'];
                        $three_info = Db::name('base_data')->field('id')->where('parent_id',$value['id'])->select();
                        if($three_info) {
                            $ids = '';
                            $arr3 = [];
                            foreach ($three_info as $k => $v) {
                                $arr3[$k] = $v['id'];
                            }
                            $ids = join(',' , $arr3);
                            $res = Db::name('product')->where('category_id|type_id|small_type_id','IN',$ids)->find();
                            if(empty($res)) {
                                Db::name('base_data')->whereIn('id', $ids)->update(['flag' => 0]);
                            } else {
                                Db::rollback();
                                $status = true;
                                $result['msg'] = '该类别下还有上架的商品';
                                $result['status'] = 201;
                                break;
                            }
                        }else{
                            Db::name('base_data')->where('id', $value['id'])->update(['flag' => 0]);
                        }
                    } else {
                        Db::rollback();
                        $status = true;
                        $result['msg'] = '该类别下还有上架的商品';
                        $result['status'] = 201;
                        break;
                    }
                }
                if($status == false) {
                    Db::commit();
                    $ids = '';
                    $ids = join(',' , $arr2);
                    Db::name('base_data')->whereIn('id', $ids)->update(['flag' => 0]);
                    Db::name('base_data')->whereIn('id', $id)->update(['flag' => 0]);
                    $result = Config::get('code.success');
                }
            }else{
                Db::name('base_data')->where('id', $id)->update(['flag' => 0]);
            }
        } else {
            $result = Config::get('code.mistake');
        }*/
        return json($result);
    }

    /**
     * 新增商品规格
     * @return \think\response\Json
     */
    public function addSpec(){
        $post = Request::instance()->post();
        if (empty($post['unit']) || empty($post['price']) || empty($post['num'])){
            $result = Config::get('code.mistake');
        }else{
            $data['product_id']         = $post['id'];
            $data['packing_proportion'] = $post['num'];
            $data['unit']               = $post['unit'];
            $data['specification']      = $post['num'].$post['unit'];
            $data['price']              = $post['price'];
            $data['is_default']         = 0;
            $data['flag']               = 1;
            $res = Db::name('product_specification')->insert($data);
            if($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }
        return json($result);
    }

    public function delSpec(){
        $post = Request::instance()->post();
        if (empty($post['id'])){
            $result = Config::get('code.mistake');
        }else{
            $res = Db::name('product_specification')->delete($post['id']);
            if($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }
        return json($result);
    }

}